package com.adopapa.ethexplorer.domain;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.adopapa.ethexplorer.service.BaseService;
import com.adopapa.ethexplorer.service.QueryHelper;
import com.adopapa.ethexplorer.utils.Tools;

@Service
public class ContractInfoService extends BaseService {

	@Autowired
	private ContractInfoRepository contractInfoRepository;

	public ContractInfo getContractInfoById(String id) {
		Optional<ContractInfo> optional = contractInfoRepository.findById(id);
		return optional.isPresent() ? optional.get() : null;
	}

	public ContractInfo getContractInfoByHash(String hash) {
		List<ContractInfo> results = contractInfoRepository.findByTxHash(hash);
		return Tools.empty(results) ? null : results.get(0);
	}

	public Long getContractNumber() {
		return contractInfoRepository.count();
	}

	public Page<ContractInfo> getContractInfoPage(int pageNo, int pageSize, ContractInfo contractInfo) {
		PageRequest pageRequest = QueryHelper.buildPageRequest(pageNo, pageSize, Order.desc("createTime"));
		Specification<ContractInfo> specification = QueryHelper.buildSpecification(contractInfo);

		Page<ContractInfo> page = contractInfoRepository.findAll(specification, pageRequest);

		return page;

	}

	public ContractInfo saveContractInfo(ContractInfo contractInfo) {
		return contractInfoRepository.saveAndFlush(contractInfo);
	}

	public void deleteContractInfo(String id) {
		contractInfoRepository.deleteById(id);
	}

	public void deleteContractInfo(ContractInfo contractInfo) {
		contractInfoRepository.delete(contractInfo);
	}

}
